package me.android.library.utils.android;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class LinuxUtil {


    /*
     * ****************************************************************
     * 子函数：获得本地MAC地址
     * ****************************************************************
     */
    public String getMacAddress() {
        StringBuilder result = new StringBuilder();
        String Mac = "";
        result = new StringBuilder(callCmd("busybox ifconfig", "HWaddr"));

        // 如果返回的result == null，则说明网络不可取

        // 对该行数据进行解析
        // 例如：eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
        if (result.toString().contains("HWaddr")) {
            Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);
            if (Mac.length() > 1) {
                Mac = Mac.replaceAll(" ", "");
                result = new StringBuilder();
                String[] tmp = Mac.split(":");
                for (String s : tmp) {
                    result.append(s);
                }
            }
        }
        return result.toString();
    }

    public String callCmd(String cmd, String filter) {
        String result = "";
        String line = "";
        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            InputStreamReader is = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(is);

            // 执行命令cmd，只取结果中含有filter的这一行
            while ((line = br.readLine()) != null && !line.contains(filter)) {
                // result += line;
                log.debug("line:{} " ,line);
            }
            result = line;
            log.debug("result:{} " , result);
        } catch (Exception e) {
            log.warn("callCmd error", e);
        }
        return result;
    }
}
